package cn.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * ClassName: CuratorFive
 * Desc: 分布式锁（如流水号生成）
 * Date： 2016/12/7
 * Created：shaom
 */
public class CuratorFive {
    static String lock_path = "/curator_lock_path";
    public static final String connectString = "master:2181,slave01:2181,slave02:2181";

    // 客户端
    static CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectString)
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(5000, 3))
            .build();

    public static void main(String[] args) throws InterruptedException {
        client.start();

        final InterProcessMutex lock = new InterProcessMutex(client, lock_path);
        final CountDownLatch downLatch = new CountDownLatch(1);

        for (int i = 0; i < 30; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        downLatch.await();
                        lock.acquire();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS");
                    String orderNo = sdf.format(new Date());
                    System.out.println("生成的订单号： " + orderNo);

                    try {
                        lock.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }

        downLatch.countDown();
//        Thread.sleep(Integer.MAX_VALUE);
    }


}
